import json
import time

import requests
import hashlib
import base64
import hmac


def gen_sign(timestamp, secret):
    # 拼接timestamp和secret
    string_to_sign = f'{timestamp}\n{secret}'
    hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    # 对结果进行base64处理
    return base64.b64encode(hmac_code).decode('utf-8')


class FeishuTalk:
    # 机器人webhook
    webhook = 'https://open.feishu.cn/open-apis/bot/v2/hook/2eb804c3-308b-4140-9f07-9d5d4113d806'

    # 发送文本消息
    def send_text_to_feishu(self, text, timestamp, sign):
        url = self.webhook
        headers = {
            "Content-Type": "application/json; charset=utf-8",
        }
        payload_message = {
            "timestamp": timestamp,
            "sign": sign,
            "msg_type": "text",
            "content": {
                # @ 单个用户 <at user_id="ou_xxx">名字</at>
                # "text": context + "<at user_id=\"bf888888\">test</at>"
                # @ 所有人 <at user_id="all">所有人</at>
                "text": f"<at user_id=\"all\">test</at>\n{text}"
            }
        }
        response = requests.post(url=url, data=json.dumps(payload_message), headers=headers)
        return response


# 执行发送文本消息
text = "生活不止眼前的苟且，还有诗和远方!"
timestamp = int(time.time())
sign = gen_sign(timestamp, 'A22hrLkMKuQDGC2hCJpGfd')
print(sign)
response = FeishuTalk().send_text_to_feishu(text, timestamp, sign)
print(response)
print(response.json())

